package com.sinux.generality.authorization.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sinux.generality.authorization.entity.SysPermission;
import com.sinux.generality.authorization.service.ISysPermissionService;
import com.sinux.generality.common.api.vo.Result;
import com.sinux.generality.common.system.util.JwtUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: SysPermissionController 
 * @Description: 各模块权限获取接口
 * @author vijay 
 * @date 2019年7月29日 上午10:48:05 
 *
 */
@Slf4j
@RestController
@RequestMapping("/permissions")
public class SysPermissionController {

	@Autowired
	private ISysPermissionService sysPermissionService;

	/**
	 * 查询用户拥有的菜单权限和按钮权限（根据TOKEN）
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{serviceName}", method = RequestMethod.POST)
	public Result<?> getUserPermissionByModule(HttpServletRequest request, @PathVariable("serviceName") String module) {
		Result<JSONObject> result = new Result<JSONObject>();
		try {
			String username = JwtUtil.getUserNameByToken(request);
			if (StringUtils.isBlank(username)) {
				return Result.error("TOKEN校验失败！");
			}
			List<SysPermission> metaList = sysPermissionService.queryByUser(username, module);
			JSONObject json = new JSONObject();
			JSONArray authjsonArray = new JSONArray();
			this.getAuthJsonArray(authjsonArray, metaList);
			json.put("urlAuth", authjsonArray);
			result.setResult(json);
			result.success("查询成功");
		} catch (Exception e) {
			result.error500("查询失败:" + e.getMessage());  
			log.error(e.getMessage(), e);
		}
		return result;
	}

	@RequestMapping(value = "/checkUserPermission", method = RequestMethod.POST)
	public Result<?> checkUserPermission(HttpServletRequest request, @RequestParam("serviceName") String module,
			@RequestParam("target") String target, @RequestParam("resource") String resource, @RequestParam("permission")String permission) {
		Result<Boolean> result = new Result<Boolean>();
		try {
			String username = JwtUtil.getUserNameByToken(request);
			if (StringUtils.isBlank(username)) {
				return Result.error("TOKEN校验失败！");
			}
			boolean allowed = false;
			switch (target) {
			case "url":
				allowed = sysPermissionService.checkUserPermission(username, module, resource, permission);
				break;

			default:
				break;
			}
			result.setResult(allowed);
			result.success("查询成功！");
		} catch (Exception e) {
			result.error500("查询失败:" + e.getMessage());  
			log.error(e.getMessage(), e);
		}
		return result;
	}
	/**
	  *  获取权限JSON数组
	 * @param jsonArray
	 * @param metaList
	 * @param parentJson
	 */
	private void getAuthJsonArray(JSONArray jsonArray,List<SysPermission> metaList) {
		for (SysPermission permission : metaList) {
			if(permission.getMenuType()==null) {
				continue;
			}
			JSONObject json = null;
			if(permission.getMenuType()==2&&"1".equals(permission.getStatus())) {
				json = new JSONObject();
				json.put("target", "url");
				json.put("name", permission.getName());
				json.put("resource", permission.getUrl());
				json.put("permission", permission.getPerms());
				json.put("description", permission.getName());
				jsonArray.add(json);
			}
		}
	}
}
